package com.sdms.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.sdms.core.auth.AuthoriseServiceImpl;
import com.sdms.core.auth.IAuthoriseService;
import com.sdms.core.auth.UnauthorisedUserException;
import com.sdms.core.login.ILoginService;
import com.sdms.core.login.LoginService;

public class MainApp
{
	private static String login = "login";
	private static String logout = "logout";
	private static String view = "view";
	private static String list = "list";
	private static String add = "add";
	private static String remove = "remove";
	private static String exit = "exit";
	private static String menu = "menu";
	private static String changePrev = "cprv";

	private static Scanner commandReader;
	private static List<String> actionList;

	private static IAuthoriseService authSvc;
	private static IDeliveryManagementSystem delMgmtSys;
	private static ILoginService loginService;

	private static String loggedUser;
	private static String loggedSession;
	private static String luTag;

	public static void main( String[] args )
	{
		authSvc = new AuthoriseServiceImpl();
		delMgmtSys = new DeliveryManagementSystem( authSvc );
		loginService = new LoginService();

		luTag = "sdms# ";

		actionList = new ArrayList<String>();
		actionList.add( login );
		actionList.add( logout );
		actionList.add( view );
		actionList.add( list );
		actionList.add( add );
		actionList.add( remove );
		actionList.add( exit );
		actionList.add( menu );
		actionList.add( changePrev );

		commandReader = new Scanner( System.in );
		printLogo();
		printMenu();

		String selectedAction = null;
		while ( !exit.equalsIgnoreCase( selectedAction ) )
		{
			selectedAction = readAction();
			processAction( selectedAction );
			println( "" );
		}
	}

	private static void processAction( String input )
	{
		if ( login.equalsIgnoreCase( input ) )
		{
			loginAction();
		}
		else if ( logout.equalsIgnoreCase( input ) )
		{
			logoutAction();
		}
		else if ( view.equalsIgnoreCase( input ) )
		{
			viewAction();
		}
		else if ( list.equalsIgnoreCase( input ) )
		{
			listAction();
		}
		else if ( add.equalsIgnoreCase( input ) )
		{
			addAction();
		}
		else if ( remove.equalsIgnoreCase( input ) )
		{
			removeAction();
		}
		else if ( exit.equalsIgnoreCase( input ) )
		{
			exitAction();
		}
		else if ( menu.equalsIgnoreCase( input ) )
		{
			menuAction();
		}
		else if ( changePrev.equalsIgnoreCase( input ) )
		{
			cprevAction();
		}
	}

	private static void loginAction()
	{
		if ( !isLoggedin() )
		{
			String un = readInput( "Enter user name : " );
//			String pw = readInput("Enter password : ");
			String pw = readPassword();
			try
			{
				String sessionId = loginService.login( un, pw );
				loggedUser = un;
				loggedSession = sessionId;
				luTag = un + "@sdms# ";
				println( un + " succesfully logged in " );
			}
			catch ( IllegalAccessException e )
			{
				// e.printStackTrace();
				println( "Username or password incorrect !" );
			}
		}
		else
		{
			println( "Already logged in as " + loggedUser );
		}
	}

	private static void logoutAction()
	{
		if ( isLoggedin() )
		{
			loginService.logOut( loggedSession );
			String user = loggedUser;
			loggedSession = null;
			loggedUser = null;
			luTag = "sdms# ";
			println( "Succesfully logged out user " + user );
		}
		else
		{
			System.out.println( "Already logged out from the system" );
		}
	}

	private static void viewAction()
	{
		if ( isLoggedin() )
		{
			String no = readInput( "Enter item number : " );
			try
			{
				DeliveryDetails details = delMgmtSys.viewDeliveryDetails( loggedSession, no );
				if ( details != null )
				{
					println( "Succesfully added the item :: Item NO. - " + details.getItemId() );
					println( "Customer : " + details.getCustomerName() + ", From : " + details.getCollectFrom() + ", To : " + details.getDestination() + ", Description : " + details.getItemIDesc() );

				}
				else
				{
					println( "Item number not found" );
				}
			}
			catch ( UnauthorisedUserException e )
			{
				println( "Unauthorised User : " + e.getMessage() );
				// e.printStackTrace();
			}
		}
		else
		{
			println( "Please logged in to the system, before view items" );
		}
	}

	private static void listAction()
	{
		if ( isLoggedin() )
		{
			try
			{
				List<DeliveryDetails> detailsList = delMgmtSys.viewDeliveryDetails( loggedSession );
				if ( detailsList != null )
				{
					for ( DeliveryDetails details : detailsList )
					{
						println( ":: Item NO. - " + details.getItemId() );
						println( "Customer : " + details.getCustomerName() + ", From : " + details.getCollectFrom() + ", To : " + details.getDestination() + ", Description : " + details.getItemIDesc() );
					}
				}
				else
				{
					println( "NO delivery details found" );
				}
			}
			catch ( UnauthorisedUserException e )
			{
				println( "Unauthorised User : " + e.getMessage() );
				// e.printStackTrace();
			}
		}
		else
		{
			println( "Please logged in to the system, before list items" );
		}
	}

	private static void addAction()
	{
		if ( isLoggedin() )
		{
			try
			{
				String cName = readInput( "Enter customer name : " );
				String collectFrom = readInput( "Enter item collect location : " );
				String destination = readInput( "Enter item destination location : " );
				String itemDesc = readInput( "Enter item description : " );
				String itemId = delMgmtSys.addItemDelivery( loggedSession, cName, collectFrom, destination, itemDesc );
				println( "Succesfully added the item :: Item NO. - " + itemId );
				println( "Customer : " + cName + ", From : " + collectFrom + ", To : " + destination + ", Description : " + itemDesc );
			}
			catch ( UnauthorisedUserException e )
			{
				// e.printStackTrace();
				println( "Unauthorised User : " + e.getMessage() );
			}
		}
		else
		{
			println( "Please logged in to the system, before add items" );
		}
	}

	private static void removeAction()
	{
		if ( isLoggedin() )
		{
			try
			{
				String itemId = readInput( "Enter delivery item number : " );
				DeliveryDetails details = delMgmtSys.cancelItemDelivery( loggedSession, itemId );
				if ( details!=null )
				{
					println( "Succesfully removed the item :: Item NO. - " + itemId );						
				}
				else
				{
					println( "Delivery item number not found" );
				}
			}
			catch ( UnauthorisedUserException e )
			{
				// e.printStackTrace();
				println( "Unauthorised User : " + e.getMessage() );
			}
		}
		else
		{
			println( "Please logged in to the system, before remove items" );
		}
	}

	private static void menuAction()
	{
		printMenu();
	}

	private static void cprevAction()
	{
		if ( isLoggedin() )
		{
			try
			{
				authSvc.changeUserPriviledges( loggedSession );				
				println( loggedUser + " succesfully altered the user priviledges " );
			}
			catch ( UnauthorisedUserException e )
			{
				println( "Unauthorised User : " + e.getMessage() );
//				e.printStackTrace();
			}
		}
		else
		{
			println( "Please logged in to the system, before add items" );
		}
	}
	
	private static boolean isLoggedin()
	{
		return loggedSession != null;
	}

	private static void exitAction()
	{
		loggedSession = null;
		loggedUser = null;
		luTag = "";
		System.out.println( "------------------------------------------------------------------------------" );
		System.out.println( "------------------------------- SYSTEM EXIT ----------------------------------" );
		System.out.println( "------------------------------------------------------------------------------" );
	}

	private static void printLogo()
	{
		System.out.println( "------------------------------------------------------------------------------" );
		System.out.println( "------------------- SECURE DELIVERY MANAGEMENT SYSTEM ------------------------" );
		System.out.println( "------------------------------------------------------------------------------" );
	}

	private static void printMenu()
	{
		println( "------------------------------------------------------------------------" );
		println( " OPTIONS :" );
		println( "	-login 		, Login to the system" );
		println( "	-logout 	, Logout from the system" );
		println( "	-view 		, View item delivery details" );
		println( "	-list 		, List all the delivery details" );
		println( "	-add 		, Add new delivery item" );
		println( "	-remove		, Remove the delivery item" );
		println( "	-menu		, Display menu" );
		println( "	-cprv		, Change current user privileges" );
		println( "	-exit 		, Exit from the system" );
		println( "------------------------------------------------------------------------" );
		println( "" );
	}

	private static String readInput( String prompt )
	{
		print( prompt );
		return readInput();
	}

	private static String readInput()
	{
		String input = commandReader.nextLine();
		while ( input == null || input.isEmpty() )
		{
			println( "Invalid input, please enter again !" );
			print( "" );
			input = commandReader.nextLine();
		}
		return input.trim();
	}

	public static String readPassword()
	{
		print( "Enter password : " );
		return new String( System.console().readPassword() );
	}

	private static String readAction()
	{
		print( "Enter the action to proceed : " );
		String input = null;
		boolean found = false;
		while ( !found )
		{
			input = commandReader.nextLine();
			if ( input != null && !input.isEmpty() )
			{
				input = input.trim();
				for ( String action : actionList )
				{
					if ( action.equalsIgnoreCase( input ) )
					{
						found = true;
						break;
					}
				}
			}
			if ( !found )
			{
				println( "Invalid action, please enter again !" );
				print( "" );
			}
		}
		return input;
	}

	private static void println( String message )
	{
		System.out.println( luTag + message );
	}

	private static void print( String message )
	{
		System.out.print( luTag + message );
	}
}
